package banner

import (
	"context"
	"fmt"
	"strings"

	"mall/common/globalkey"
	"mall/common/utils/pointy"
	"mall/service/attachment/rpc/attachmentclient"
	"mall/service/backend/api/internal/svc"
	"mall/service/backend/api/internal/types"
	"mall/service/backend/common/enum/errorcode"
	"mall/service/backend/common/errorx"
	"mall/service/backend/rpc/backendclient"

	"github.com/zeromicro/go-zero/core/logx"
)

type UpdateBannerLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewUpdateBannerLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UpdateBannerLogic {
	return &UpdateBannerLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *UpdateBannerLogic) UpdateBanner(req *types.UpdateBannerReq) (resp *types.BaseMsgResp, err error) {
	if len(req.Ids) > 0 {
		res, err := l.svcCtx.BackendRpc.UpdateBanner(l.ctx, &backendclient.BannerInfo{
			Status: req.Status,
			Ids:    req.Ids,
		})
		if err != nil {
			return nil, err
		}

		return &types.BaseMsgResp{
			Success: true,
			Msg:     l.svcCtx.Trans.Trans(l.ctx, res.Msg),
		}, nil
	}

	if req.Id == nil || *req.Id == 0 {
		return nil, errorx.NewCodeError(errorcode.InvalidArgument,
			l.svcCtx.Trans.Trans(l.ctx, "common.validationError"))
	}

	if req.PicUrl != nil && len(strings.TrimSpace(*req.PicUrl)) == 0 {
		return nil, errorx.NewCodeError(errorcode.InvalidArgument,
			l.svcCtx.Trans.Trans(l.ctx, "banner.picUrlRequired"))
	}

	var skipMedia bool
	if req.SkipMedia != nil && *req.SkipMedia > 0 {
		skipMedia = true
	}

	newThumbMap := make(map[string]*types.MediaInfo)
	var newMediaIds []string // 用于查询 attachmentRpc
	var thumbnail *uint32 = pointy.GetPointer(uint32(1))
	var newMedia []*backendclient.MediaInfo
	var newAttachmentIds []string            // 用于主动通知 attachmentRpc
	if !skipMedia && len(req.NewThumb) > 0 { // 缩略图新图片
		for _, v := range req.NewThumb {
			if v.Id != nil && len(*v.Id) > 0 {
				if _, ok := newThumbMap[*v.Id]; !ok { // 忽略重复id
					newThumbMap[*v.Id] = v
					newMediaIds = append(newMediaIds, *v.Id)
				}
			} else {
				newMedia = append(newMedia, &backendclient.MediaInfo{
					Uid:      v.Uid,
					Order:    v.Order,
					Url:      v.Url,
					Name:     v.Name,
					MimeType: v.MimeType,
					AltText:  v.AltText,
					MetaData: v.MetaData,
				})
			}
		}
	}

	if len(newMediaIds) > 0 {
		res, err := l.svcCtx.AttachmentRpc.BackendGetFileList(l.ctx, &attachmentclient.FileListReq{
			Ids: pointy.GetPointer(strings.Join(newMediaIds, ",")),
		})
		if err != nil {
			return nil, err
		}

		if len(res.List) > 0 {
			for _, v := range res.List {
				if v.Id != nil && len(*v.Id) > 0 {
					mediaId := *v.Id
					var url string
					if v.Url != nil && len(*v.Url) > 0 {
						url = fmt.Sprintf("%s%s", l.svcCtx.Config.NfsConf.StaticUrl, *v.Url)
					}
					var uri string
					if v.Path != nil && len(*v.Path) > 0 {
						uri = fmt.Sprintf("%s%s", l.svcCtx.Config.NfsConf.ProxyUrl, *v.Path)
					}
					if len(url) == 0 {
						url = uri
					}

					if media, ok := newThumbMap[mediaId]; ok {
						newMedia = append(newMedia, &backendclient.MediaInfo{
							Uid:       media.Uid,
							Id:        v.Id,
							Thumbnail: thumbnail,
							Order:     media.Order,
							Uri:       media.Url,
							Url:       pointy.GetPointer(url),
							Name:      media.Name,
							MimeType:  media.MimeType,
							AltText:   media.AltText,
							MetaData:  media.MetaData,
						})
						newAttachmentIds = append(newAttachmentIds, *v.Id)
					}
				}
			}
		}
	}

	var adId *uint64
	var adType *uint32
	if req.LinkType != nil && *req.LinkType > 0 { // 相对路径，接收广告类型和广告ID
		adType = req.AdType
		adId = req.AdId
	}

	res, err := l.svcCtx.BackendRpc.UpdateBanner(l.ctx, &backendclient.BannerInfo{
		Id:        req.Id,
		PicUrl:    req.PicUrl,
		Type:      req.Type,
		Title:     req.Title,
		LinkType:  req.LinkType,
		LinkUrl:   req.LinkUrl,
		AdType:    adType,
		AdId:      adId,
		Status:    req.Status,
		Sort:      req.Sort,
		StartedAt: req.StartedAt,
		EndedAt:   req.EndedAt,
		NewMedia:  newMedia,
		SkipMedia: req.SkipMedia,
	})
	if err != nil {
		return
	}

	if len(newAttachmentIds) > 0 {
		_, err = l.svcCtx.AttachmentRpc.CreateFileLog(l.ctx, &attachmentclient.CreateFileLogReq{
			FileIds:    newAttachmentIds,
			Put:        pointy.GetPointer(uint32(1)),
			ObjectId:   req.Id,
			ObjectType: pointy.GetPointer(uint32(globalkey.AttachmentLogTypeBanner)),
		})
		if err != nil {
			logx.Errorw("UpdateBanner CreateFileLog err", logx.Field("detail", err.Error()))
		}
	}

	return &types.BaseMsgResp{
		Success: true,
		Msg:     l.svcCtx.Trans.Trans(l.ctx, res.Msg),
	}, nil
}
